﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Linq;
using System.Linq;
using System.Security.Cryptography;
using DevExpress.XtraEditors;


namespace UI_PMQLThuPhi_LMD
{
    public delegate void DangNhapEventHandler(object sender, Boolean e);

    public partial class XtraUserControl1 : DevExpress.XtraEditors.XtraUserControl
    {
        public event DangNhapEventHandler dangNhapThanhCong;

        public XtraUserControl1()
        {
            InitializeComponent();

            // Key for encryption
            SystemInfo.pub_KeyForEncrytion = "ThuPhiVeSinh";

            // Server name
            SystemInfo.pub_ServerName = System.Configuration.ConfigurationManager.AppSettings["serverName"];
            txtTenMayChu.Text = SystemInfo.pub_ServerName;

            // Database name
            SystemInfo.pub_DatabaseName = System.Configuration.ConfigurationManager.AppSettings["databaseName"];

            // Database user name
            SystemInfo.pub_UserName = System.Configuration.ConfigurationManager.AppSettings["databaseUserName"];
            txtDatabaseUser.Text = SystemInfo.pub_UserName;

            // Application user password
            if (System.Configuration.ConfigurationManager.AppSettings["databaseUserPassword"] != null &&
                SystemInfo.pub_KeyForEncrytion != null)
            {
                   SystemInfo.pub_UserPassword = EncryptionUtility.DecryptString(
                System.Configuration.ConfigurationManager.AppSettings["databaseUserPassword"],
                SystemInfo.pub_KeyForEncrytion);
            txtDatabaseUserPassword.Text = SystemInfo.pub_UserPassword;
            }
         
            // Application user name
            SystemInfo.pub_AppUserName = System.Configuration.ConfigurationManager.AppSettings["applicationUsername"];
            txtTenDangNhap.Text = SystemInfo.pub_AppUserName;

            // Application user_password
            if (System.Configuration.ConfigurationManager.AppSettings["applicationUserPassword"] != null &&
               SystemInfo.pub_KeyForEncrytion != null)
            {
                SystemInfo.pub_AppUserPassword = EncryptionUtility.DecryptString(
                    System.Configuration.ConfigurationManager.AppSettings["applicationUserPassword"],
                    SystemInfo.pub_KeyForEncrytion);
                txtMatKhau.Text = SystemInfo.pub_AppUserPassword;
            }

            // Connection string
            SystemInfo.pub_ConnString = "user id = " + SystemInfo.pub_UserName + ";" +
                                            "password = " + SystemInfo.pub_UserPassword + ";" +
                                            "server = " + SystemInfo.pub_ServerName + ";" +
                                            "Trusted_Connection = yes;" +
                                            "database = " + SystemInfo.pub_DatabaseName + ";" +
                                            "connection timeout=30";
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            DataClasses1DataContext db = new DataClasses1DataContext(SystemInfo.pub_ConnString);

            Boolean dangNhapFlag = false;

            // query database
            var nguoiDung = from c in db.Nguoi_Dungs select c ;

            Cursor.Current = Cursors.WaitCursor;

            foreach (var c in nguoiDung)
            {
                if (c.ND_Ten == txtTenDangNhap.Text &&
                    EncryptionUtility.DecryptString(c.ND_MatKhau, SystemInfo.pub_KeyForEncrytion) == txtMatKhau.Text)
                {
                    dangNhapFlag = true;

                    // Thông tin phân quyền
                    SystemInfo.pub_QuyenSuDung = c.ND_QuyenSuDung;

                    break;
                }
            }

            if (dangNhapFlag == true)
            {
                XtraMessageBox.Show("Đăng nhập thành công.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                
                // Application user name
                SystemInfo.pub_AppUserName = txtTenDangNhap.Text;

                // Application user_password
                SystemInfo.pub_AppUserPassword = txtMatKhau.Text;

                if (checkEdit1.Checked == true)
                {
                    // Lưu vào app.config            
                    AppConfigFileSetting.UpdateAppSettings("applicationUsername", 
                        SystemInfo.pub_AppUserName);

                    //Encrypt the password
                    string EncryptedAppUserPassword = EncryptionUtility.EncryptString(
                            SystemInfo.pub_AppUserPassword, SystemInfo.pub_KeyForEncrytion);
                    AppConfigFileSetting.UpdateAppSettings("applicationUserPassword", EncryptedAppUserPassword);
                }

                else
                {
                    // Lưu giá trị rỗng vào app.config            
                    AppConfigFileSetting.UpdateAppSettings("applicationUsername", " ");

                    //Encrypt the password
                    AppConfigFileSetting.UpdateAppSettings("applicationUserPassword", " ");
                }

                Cursor.Current = Cursors.Default;

                // Raised the event Đăng nhập thành công
                if (dangNhapThanhCong != null)
                {
                    dangNhapThanhCong(this, true);
                }
            }

            else
            {
                XtraMessageBox.Show("Đăng nhập thất bại.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Cursor.Current = Cursors.Default;
            }
        }

        private void btKetNoi_Click(object sender, EventArgs e)
        {
            if (lblTenMayChu.Visible == false)
            {
                lblTenMayChu.Visible = true;
                txtTenMayChu.Visible = true;
                lblTaiKhoan.Visible = true;
                txtDatabaseUser.Visible = true;
                lblMatKhau.Visible = true;
                txtDatabaseUserPassword.Visible = true;
            }

            else if (lblTenMayChu.Visible == true)
            {
                // Server name
                SystemInfo.pub_ServerName = txtTenMayChu.Text;

                // Database name
                SystemInfo.pub_DatabaseName = "ThuPhiVeSinh";

                // Database username
                SystemInfo.pub_UserName = txtDatabaseUser.Text;

                // User password
                SystemInfo.pub_UserPassword = txtDatabaseUserPassword.Text;

                // Connection string
                SystemInfo.pub_ConnString = "user id = " + SystemInfo.pub_UserName + ";" +
                                              "password = " + SystemInfo.pub_UserPassword + ";" +
                                              "server = " + SystemInfo.pub_ServerName + ";" +
                                              "Trusted_Connection = no;" +
                                              "database = " + SystemInfo.pub_DatabaseName + ";" +
                                              "connection timeout=30";

                //Test connection
                SqlConnection myConnection = new SqlConnection(SystemInfo.pub_ConnString);

                try
                {
                    myConnection.Open();

                    XtraMessageBox.Show("Kết nối thành công.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    String newConnecionString = "Data Source = " + txtTenMayChu.Text + ";" +
                                                "Initial Catalog = " + "ThuPhiVeSinh" + ";" +
                                                "User ID = " + txtDatabaseUser.Text + ";" +
                                                "Password = " + txtDatabaseUserPassword.Text;

                    //Write to app.config
                    AppConfigFileSetting.UpdateConnectionStringValue(newConnecionString);
                    AppConfigFileSetting.UpdateAppSettings("serverName", SystemInfo.pub_ServerName);
                    AppConfigFileSetting.UpdateAppSettings("databaseName", SystemInfo.pub_DatabaseName);
                    AppConfigFileSetting.UpdateAppSettings("databaseUsername", SystemInfo.pub_UserName);

                    //Encrypt the password
                    string EncryptedDatabaseUserPassword = EncryptionUtility.EncryptString(SystemInfo.pub_UserPassword,
                                                                             SystemInfo.pub_KeyForEncrytion);
                    AppConfigFileSetting.UpdateAppSettings("databaseUserPassword", EncryptedDatabaseUserPassword);

                    lblTenMayChu.Visible = false;
                    txtTenMayChu.Visible = false;
                    lblTaiKhoan.Visible = false;
                    txtDatabaseUser.Visible = false; 
                    lblMatKhau.Visible = false;
                    txtDatabaseUserPassword.Visible = false;
                }
                catch (Exception)
                {
                    XtraMessageBox.Show("Kết nối không thành công.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                finally
                {
                    myConnection.Close();
                }
            }

         
        }
    }
}
